import type {Request} from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {matchRoutes} from 'react-router-dom';
import {createStaticRouter, StaticHandlerContext, StaticRouterProvider} from 'react-router-dom/server';
import {handler} from './router/index.server';
import {HEAD_TO_ROUTE, routes} from './router/routeConfig';

export async function render({request}: {request: Request}) {
    // eslint-disable-next-line no-shadow
    const createFetchRequest = (request: Request) => {
        const origin = `${request.protocol}://${request.get('host')}`;
        const url = new URL(request.originalUrl, origin);
        return new Request(url.href, {});
    };
    const context = (await handler.query(createFetchRequest(request))) as StaticHandlerContext;
    const router = createStaticRouter(handler.dataRoutes, context);
    const stream = ReactDOMServer.renderToStaticNodeStream(
        <StaticRouterProvider
            router={router}
            context={context}
        />
    );

    const routeList = matchRoutes(routes, request.originalUrl) || [];
    const heads = routeList.map(item => {
        // eslint-disable-next-line max-len
        const curHead: Record<string, any> = HEAD_TO_ROUTE.find(headInfo => item.pathname.includes(headInfo.path)) || {};
        return curHead?.head;
    }).filter(Boolean) as React.ComponentType[];
    const head = ReactDOMServer.renderToString(
        <>
            {
                heads.length
                    ? heads.map((HeadItem, index) => (
                        <HeadItem key={index} />
                    ))
                    : <title>toolkit</title>
            }
        </>
    );

    return {html: stream, head};
}
